import axios from 'axios'
import router from '@/router'
// import './permission'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      // config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.dir(error.response.status)
    if (error.response.status === 401) {
      // 清除token和用户信息
      this.$store.dispatch('user/removeToken')
      // 跳转到登录页
      router.push('/login')
    }
    Message.error(error.response.data.msg)
    return Promise.reject(error)
  }
)

// 路由前置守卫
// 设置白名单
const whiteList = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRouter(perms) {
  const newArr = perms.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
function getSecondRouter(perms) {
  const newArr = perms.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}}`
  })
  return [...new Set(newArr)]
}

router.beforeEach(async(to, from, next) => {
  const token = getToken()
  // 有token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断是否获取过用户信息
      if (!store.state.user.profile?.id) {
        // 调用vuex中的action 获取用户权限信息
        const perms = await store.dispatch('user/getUserInfo')
        // console.log(perms)
        const firstRouter = getFirstRouter(perms)
        console.log(firstRouter)
        const secondRouter = getSecondRouter(perms)
        console.log(secondRouter)
      } else {
        next()
      }
    }
  // 无token
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default service
